import { JKManager } from "../JKManager"
import { LocalizedLabel } from "./LocalizedLabel"

const LanguageCodeKey = `LanguageCodeKey`

/**
 * 多语言工具单例
 */
export class Language {
    private _languageCode: string = cc.sys.languageCode
    private _lanMap: { [key: string]: string }
    private _paramsMap: { [key: string]: (number | string)[] } = cc.js.createMap()

    set languageCode(languageCode) {
        this._languageCode = languageCode
        JKManager.LocalStorage.setData(LanguageCodeKey, this._languageCode)
    }
    get languageCode(): string {
        return JKManager.LocalStorage.getData(LanguageCodeKey) || this._languageCode
    }

    /**
     * 初始化并切换本地语言
     * @param languageCode 地区语言码
     * @param call 回调
     */
    init(languageCode: string, call: () => void = null) {
        cc.log(`${cc.js.getClassName(this)} init`)

        this.languageCode = languageCode.replace(`-`, `_`).toLocaleLowerCase()
        cc.resources && cc.resources.load(`JKCore/Script/Language/${this.languageCode}`, (err, file: cc.JsonAsset) => {
            if (err) {
                cc.warn(`${cc.js.getClassName(this)} init There is no language config ${this.languageCode}`)
                let codes = this.languageCode.split(`_`)
                if (codes.length > 1) {
                    if (codes[0] === `zh` && codes[1] !== `cn` && codes[1] !== `tw`) {
                        codes[1] = `tw`
                        this.languageCode = codes.join(`_`)
                        cc.warn(`${cc.js.getClassName(this)} init Check ${this.languageCode} ...`)
    
                        this.init(this.languageCode, call)
                    } else {
                        cc.warn(`${cc.js.getClassName(this)} init Check ${codes[0]} ...`)
    
                        this.init(codes[0], call)
                    }
                } else {
                    cc.error(`${cc.js.getClassName(this)} init `, err)
                }
            } else {
                cc.log(`${cc.js.getClassName(this)} init Found language ${this.languageCode}`)

                this._lanMap = file.json
                JKManager[`${this.languageCode}Config`] = this._lanMap

                // 刷新界面显示
                !CC_EDITOR && cc.Canvas.instance.node.getComponentsInChildren(LocalizedLabel).forEach(lab => {
                    lab.textKey && lab.refreshText(lab.textKey, ...(this._paramsMap[lab.textKey] || []))
                })

                call && call()
            }
        })
    }

    //==============================================================================================================================
    //========================================================= 内部方法 ============================================================
    //==============================================================================================================================

    //==============================================================================================================================
    //========================================================= 外部方法 ============================================================
    //==============================================================================================================================

    /**
     * 根据键值获取文本
     * @param textKey 文本键值
     * @param args 参数，按顺序替换替换$[param]
     */
    getText(textKey: string, ...args: (number | string)[]): string {
        // cc.log(`${cc.js.getClassName(this)} get textKey = ${textKey}`)

        let str: string = this._lanMap && this._lanMap[textKey] || textKey || ``,
            index = 0
        str = str.replace(/\$\[.*?\]/g, (subStr) => {
            let newSubStr = args[index] ? args[index].toString() : ``
            index++

            return newSubStr
        })
        this._paramsMap[textKey] = args

        return str
    }
}